package com.gs.config;

import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.interceptor.*;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @ProjectName: springbootmybitstest
 * @Package: com.gs.config
 * @Description: java类作用描述
 * @Author: Administrator
 * @CreateDate: 2018/6/22 10:16
 * @UpdateUser: Administrator
 * @UpdateDate: 2018/6/22 10:16
 * @UpdateRemark: The modified content
 * @Version: 1.0
 **/

@Configuration
public class TxAnoConfig {

    private static final String transactionExecution = "execution (* com.gs.service.*.*(..))";


    @Bean("txManager")
    public PlatformTransactionManager annotationDrivenTransactionManager(@Qualifier("dataSource") DataSource dataSource) {

        return new DataSourceTransactionManager(dataSource);
    }




    // 事务的实现Advice
    @Bean
    public TransactionInterceptor txAdvice(@Qualifier("txManager")PlatformTransactionManager m) {

        Properties attributes = new Properties();
        attributes.setProperty("add*", "PROPAGATION_REQUIRED,-Exception");
        attributes.setProperty("insert*", "PROPAGATION_REQUIRED,-Exception");
        attributes.setProperty("save*", "PROPAGATION_REQUIRED,-Exception");
        attributes.setProperty("update*", "PROPAGATION_REQUIRED,-Exception");
        attributes.setProperty("delete*", "PROPAGATION_REQUIRED,-Exception");

        //只读配置
        attributes.setProperty("get*", "PROPAGATION_REQUIRED,-Exception,readOnly");
        attributes.setProperty("query*", "PROPAGATION_REQUIRED,-Exception,readOnly");
        attributes.setProperty("find*", "PROPAGATION_REQUIRED,-Exception,readOnly");
        TransactionInterceptor txAdvice = new TransactionInterceptor(m, attributes);
        return txAdvice;
    }

    // 切面的定义,pointcut及advice
    @Bean
    public Advisor txAdviceAdvisor(@Qualifier("txAdvice") TransactionInterceptor txAdvice) {
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(transactionExecution);
        return new DefaultPointcutAdvisor(pointcut, txAdvice);
    }


}
